package com.nm.web.controller;

import com.nm.commons.exception.SupperException;
import com.nm.orm.pojo.MenuEntity;
import com.nm.service.MenuService;
import com.nm.service.output.MenuEasy;
import com.nm.web.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping(path = "/menu")
public class MenuController extends BaseController {

    @Autowired
    private MenuService menuSvc;

    /**
     * 菜单主view
     */
    @RequestMapping(path = "")
    public ModelAndView index() {
        ModelAndView model = new ModelAndView();
        model.setViewName("/admin/menu/index");
        return model;
    }

    /**
     * 查询所有菜单
     *
     * @return
     */
    @RequestMapping(path = "/all", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<List<MenuEasy>> findAll()
            throws SupperException {

        List<MenuEasy> output = menuSvc.findAll();

        return getResult(output);
    }

    /**
     * 增加菜单视图
     */
    @RequestMapping(path = "/add", method = RequestMethod.GET)
    public ModelAndView add() throws SupperException {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/menu/info");
        modelAndView.addObject("title", "增加菜单");
        return modelAndView;
    }

    /**
     * 增加修改菜单数据提交
     */
    @RequestMapping(path = "/datapost")
    @ResponseBody
    public ResponseEntity<Result> dataPost(@RequestBody MenuEntity menuEntity)
            throws SupperException {
        menuSvc.update(menuEntity);

        return getResult(null);
    }

    /**
     * 查新更新对象 展示修改视图
     *
     * @param id 菜单ID
     * @return
     */
    @RequestMapping(path = "/update/{id}", method = RequestMethod.GET)
    public ModelAndView update(@PathVariable("id") String id) throws SupperException {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/menu/info");

        MenuEntity entity = menuSvc.getById(id);

        modelAndView.addObject("title", "修改菜单");
        modelAndView.addObject("menu", new Result(entity));
        return modelAndView;
    }


    /**
     * 删除数据
     *
     * @param id 菜单ID
     * @return
     */
    @RequestMapping(path = "/delete/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public ResponseEntity<Result> delete(@PathVariable("id") String id) throws SupperException {

        menuSvc.deleteById(id);

        return getResult(null);
    }

}
